package com.tvunetworks.center.user.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
 * @program:
 * @description:
 * @author HenryChen
 * @create: 9/27/2019 2:33 PM
 **/
public class GZipUtil {   
    


    /**
     // 压缩
     * @param str str
     * @return String
     * @throws IOException 编译
     */
    public static String compress(String str) throws IOException {
       if (str == null || str.length() == 0) {   
        return str;   
      }   
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       GZIPOutputStream gzip = new GZIPOutputStream(out);
       gzip.write(str.getBytes("UTF-8"));
       gzip.close();   
      return out.toString("ISO-8859-1");   
     }   


    /**
     // 解压缩
     * @param str  String
     * @return str
     * @throws IOException 编译
     */
    public static String uncompress(String str) throws IOException {
       if (str == null || str.length() == 0) {   
         return str;   
     }   
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      ByteArrayInputStream in = new ByteArrayInputStream(str
           .getBytes("ISO-8859-1"));   
       GZIPInputStream gunzip = new GZIPInputStream(in);
       byte[] buffer = new byte[256];   
       int n;   
      while ((n = gunzip.read(buffer))>= 0) {   
       out.write(buffer, 0, n);   
       }   
       // toString()使用平台默认编码，也可以显式的指定如toString(&quot;GBK&quot;)   
       return out.toString("UTF-8");
     }   
     
     // 测试方法
    /**
     *
     * @param args args
     * @throws IOException 编译
     */
     public static void main(String[] args) throws IOException {
            
         //测试字符串   
        String str="{\"gpsnocontainwifi3g\":[{\"timestamp\":1495431115274,\"longitude\":\"121.02539\",\"latitude\":\"32.54681\",\"accuracy\":\"0\"}],\"msgv\":\"1.0\",\"peerId\":\"5A9D1AC3E3657D97\",\"time_sec\":1495431115274}";
            
         System.out.println("原长度："+str);
            
         System.out.println("压缩后："+GZipUtil.compress(str));
            
       System.out.println("解压缩："+GZipUtil.uncompress(GZipUtil.compress(str)));
     }   
    
   }  
